<template>
  <div class="container">
    <div class="tableColumns">
      <div class="left-tree">
          <span class="title-span">
              <span>{{spanText}}</span>
          </span>
          <el-input
                  class="unit-search"
                  placeholder="搜索单位名称"
                  :suffix-icon="Search"
                  v-model="filterText"
          />
        <el-tree
            ref="treeRef"
            node-key="id"
            :current-node-key="currentNodeKey"
            :data="companyData"
            :props="defaultProps"
            default-expand-all
            :expand-on-click-node="false"
            highlight-current

            :filter-node-method="filterNode"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node" @click="handleNodeClick(data)">
              <span class="custom-tree-node-left">
                <span class="custom-tree-node-left-label" :title="node.label">{{ node.label }}</span>
              </span>
              <span class="oper">
                    <el-icon
                        class="el-input__icon"
                        color="#427CC9" v-if="data.level!=-1&&data.level!=3&&(data.employeeIds==null||data.employeeIds=='')"
                        @click="e => addEvent(data, e)"
                    >
                      <CirclePlus/>
                    </el-icon>
                    <el-icon
                        class="el-input__icon"
                        color="#427CC9" v-if="data.level>0"
                        @click="editEvent(data, node)"
                    >
                      <EditPen/>
                    </el-icon>
                    <el-popconfirm
                        title="是否删除?"
                        confirmButtonText="确定"
                        cancelButtonText="取消"
                        @confirm="() => deleteTypeFn(data, node)"
                    >
                      <template #reference>
                        <el-icon
                            class="el-input__icon"
                            color="#e13e53" v-if="data.level>0">
                          <Delete/>
                        </el-icon>
                      </template>
                    </el-popconfirm>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="right-columns">
        <div class="table-select">
            <span class="title-span">
              <span>{{spanText2}}</span>
            </span>
            <el-form label-position="right">
              <div style="display: flex;justify-content: space-between;align-items: flex-start;">
                <el-row :gutter="24" style="flex:1">
                    <el-col :span="6">
                        <el-form-item label="人员姓名：" label-width="100px">
                            <el-input placeholder="请输入姓名" v-model="searchModel.name"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="岗位：" label-width="100px">
                          <el-select v-model="searchModel.position" placeholder="请选择" clearable>
                            <el-option
                                v-for="item in postList"
                                :key="item.positionId"
                                :label="item.name"
                                :value="item.positionId"
                            />
                          </el-select>
                        </el-form-item>
                    </el-col>
<!--                    <el-col :span="8">-->
<!--                        <el-form-item label="航站楼：" label-width="100px" style="display: flex;">-->
<!--                            <el-checkbox label="T3航站楼 24" size="large" />-->
<!--                            <el-checkbox label="T5航站楼  12" size="large" />-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->

                </el-row>
              <div style="justify-content: flex-end;display: flex">
                <el-button @click="searchReset">清空</el-button>
                <el-button
                    type="primary"
                    @click="searchChange"
                >查询</el-button>
              </div>
              </div>
            </el-form>

        </div>
        <div class="table-commons">
            <span class="title-span">
                <span>{{ spanText3 }}</span>
                <div style="display: flex;align-items: center">
                    <el-button
                        type="primary"
                        @click="addFn"
                        :disabled="addLoading"
                    >添加</el-button>
                    <el-popconfirm
                        title="是否移除?"
                        confirmButtonText="确定"
                        cancelButtonText="取消"
                        @confirm="() => deletepeoFn(null)"
                    >
                        <template #reference>
                            <el-button
                                class="link-btn"
                                plain
                                type="danger"
                                :disabled="showRestoreBtn"
                            >移除</el-button>
                        </template>
                    </el-popconfirm>
                </div>
            </span>
            <table-common
                :loading="loading"
                :columns="exampleColumns"
                :pagination="pager"
                :table-data="tableData"
                @size-change="sizeChange"
                @current-change="myChangeCurrent"
                @selection-change="selectionChangeHandle"
                stripe
                :height="'500px'"
            >
                <template #action="{ row }">
                    <!-- 自定义操作栏示例  -->
                    <el-popconfirm
                        title="是否移除?"
                        confirmButtonText="确定"
                        cancelButtonText="取消"
                        @confirm="() => deletepeoFn(row)"
                    >
                        <template #reference>
                            <el-button
                                class="link-btn"
                                link
                                type="danger"
                            >移除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </table-common>
        </div>
      </div>
    </div>
    <!-- 新增/编辑分组弹窗   -->
    <edit-dialog class="maintenance" :centerDialogVisible="addGroupDialogVisible" :tilte="addGroupTitle" :key="timer"
                 align-center :defaultButton="false" :width="500" @cancel="handleCancel">
      <template #content>
        <el-form :model="ruleForm" :rules="rules" ref="goodsTypeFormRef">
          <el-form-item label-width="80px" label="父级" prop="parentGroup">
            <el-input v-model="ruleForm.parentName" disabled/>
          </el-form-item>
          <el-form-item label-width="80px" label="分组名称" prop="name">
            <el-input v-model="ruleForm.name" maxlength="15"/>
          </el-form-item>
          <el-form-item label-width="80px" label="排序" prop="sortNo">
            <el-input v-model="ruleForm.sortNo" type="number"/>
          </el-form-item>
        </el-form>
      </template>
      <template #custom>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="saveBtn" @click="handleTransferSubmit(goodsTypeFormRef)">保存</el-button>
        </span>
      </template>
    </edit-dialog>
    <!-- 编辑人员 -->
    <Edit :visible="addPeoperVisible" :info="selectGroup" @cancel="handleCancel" @ok="handleOk"/>
  </div>
</template>

<script setup lang="ts">
import {Search} from "@element-plus/icons-vue";
import {ElMessage, ElTree, FormInstance} from "element-plus";
import type { FormRules } from 'element-plus'
import {nextTick, onMounted, ref, reactive, computed, toRef, toRaw, watch} from "vue";
import editDialog from '@/components/editDialog/index.vue';
import addInnerUser from "./componens/AddInnerUser.vue";
import {exampleColumns} from "./config/columns";
import TableCommon from "@/components/TableCommon/index.vue";
import {useStore} from "vuex";
import Edit from './edit.vue'
import {
  delUsers, getPostList,
  getScheduleGroup, getUserListByScheduleGroup,
  scheduleGroupAdd,
  scheduleGroupUpdate
} from "@/api/quality/scheduleGroup";
const spanText = ("组织架构及分组信息")
const spanText2 = ("数据筛选")
const spanText3 = ("信息列表")
const addGroupDialogVisible = ref(false); // 新增/编辑弹窗是否打开
const addLoading = ref(true); // 添加按钮加载动画
const addPeoperVisible = ref(false); // 添加弹窗是否打开
const addGroupTitle = ref<string>(""); // 新增/编辑弹窗标题
const addPerperTitle = ref<string>(""); // 添加弹窗标题
const timer = ref(); // 弹窗时间戳
const goodsTypeFormRef = ref<FormInstance>()
// 新增/编辑 表单验证
const ruleForm = ref({
  name: '',
  sortNo: '',
  parentId: '',
  parentName: '',
  level: '',
  id: undefined,
  createDept: undefined
}); // 新增/编辑分组表单
const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: '请填写分组名称',
      trigger: 'blur',
    },
  ],
  sortNo: [
    {
      required: true,
      message: '请填写排序',
      trigger: 'blur',
    },
    { pattern: /^([0-9]|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/, message: '范围在0-255',trigger: 'blur'}
  ]
})
const searchModel = ref({
  position: '',
  name: ''
})
const saveBtn = ref(false); // 确认按钮加载动画
const loading = ref(false); // 表格加载动画
const pager = reactive({ // 表格分页
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0,
});
const {getters} = useStore();
const tableData = ref([]); // 表格数据
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
const organizes = computed(() => getters['user/getOrganTree']);
const companyData = ref([]); // 左侧组织架构数据
const selectGroup = ref({})
const postList = ref([])
const defaultProps = {
  children: 'children',
  label: 'name',
}; // 左侧组织架构数据回显
//默认选中组织目录第一个
const treeRefs = ref<any>(null)
const currentNodeKey = ref("")
const dataListSelections = ref([])
const showRestoreBtn = ref(true)
const getTopOne = (data: any) => {
  if (data.children && data.children.length > 0) {
    getTopOne(data.children[0])
  } else {
    nextTick(() => {
      currentNodeKey.value = data.id
      treeRefs.value.setCurrentKey(currentNodeKey.value)
    })
  }
}
const filterText = ref('')
const treeRef = ref('')
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}
// 左侧组织架构节点事件
const handleNodeClick = (data) => {
  console.log(data);
  if(data.parentId==-1||(data.children&&data.children.length>0)){
    addLoading.value=true
    selectGroup.value={}
  }else{
    addLoading.value=false
    selectGroup.value=data
    getList()
  }

}

const findByCondition = (data:any,list:any)=>{
  for (let i = 0; i < data.length; i++) {
    var node = data[i];
    if (node.id === selectGroup.value.id) { // 为true跳出循环
        node.employeeIds=list.join(',')
    } else {
      if (node.children != null) {
        findByCondition(node.children,list);
      }
    }
  }
}
// 新增分组
const addEvent = (data: any, e: Event) => {
  addGroupDialogVisible.value = true;
  addGroupTitle.value = "新增分组";
  ruleForm.value.parentId = data.parentId == -1 ? "" : data.id;
  // 层级3和4的时候，默认为2级机构
  ruleForm.value.parentName = data.name;
  ruleForm.value.level = data.level;
  ruleForm.value.id = data.id;
  ruleForm.value.createDept = data.createDept ? data.createDept : data.id
}

// 编辑分组
//编辑分类
const editEvent = (data: any, node: any) => {
  addGroupDialogVisible.value = true;
  addGroupTitle.value = "编辑分组";
  ruleForm.value.parentId = data.parentId;
  // 层级3和4的时候，默认为2级机构
  ruleForm.value.parentName = data.parentName;
  ruleForm.value.level = data.level;
  ruleForm.value.id = data.id
  ruleForm.value.createDept = data.createDept
  ruleForm.value.name = data.name
  ruleForm.value.sortNo = data.sortNo
}

// 删除分组信息
const deleteTypeFn = async (data: any, node: any) => {
  const res = await scheduleGroupUpdate({
    id: data.id,
    isDeleted: 1
  });
  if (res?.code === '1') {
    ElMessage.success("删除成功");
    handleCancel()
    selectGroup.value={}
    tableData.value = []
   // getList()
    geTreeData()
  } else {
    ElMessage.error(res?.message || '操作失败，请重试！');
  }
}

// 移除班组人员信息
const deletepeoFn = async (data: any) => {
  // 批量移除   单个移除
  let employeeIds = []
  if (data == null) {
    dataListSelections.value.forEach(item => {
      employeeIds.push(item.staffId)
    })
    //多个删除
  } else {
    //单个删除
    employeeIds.push(data.staffId)
  }
  const res = await delUsers({
    id: selectGroup.value.id,
    employeeIds: employeeIds.join(',')
  })
  if (res?.code === '1') {
    ElMessage.success('移除成功')
    handleCancel()
    findByCondition(companyData.value,employeeIds)
    getList()
  } else {
    ElMessage.error(res?.message || '移除失败')
  }

}

// 新增/弹窗确认按钮
const handleTransferSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let fetch = scheduleGroupAdd;
      saveBtn.value = true
      const payload: any = {...ruleForm.value};
      if (addGroupTitle.value == '编辑分组') {
        fetch = scheduleGroupUpdate;
        payload.mender = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
      } else {
        payload.creator = {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          userName: userInfo.value.userName,
          organId: userInfo.value.organId || '',
          organName: userInfo.value.organName || ''
        }
        payload.level++
        payload.id = undefined
      }
      const res = await fetch(payload);
      if (res?.code === '1') {
        if (addGroupTitle.value == '编辑分组') {
          ElMessage.success("编辑成功")
        } else {
          ElMessage.success("新增成功")
        }
        handleCancel();

        geTreeData()
      } else {
        ElMessage.error(res?.message || '操作失败，请重试！');
        saveBtn.value = false
      }


    }
  })
}
//获取组织架构下人员
// 添加分组人员信息
const addFn = () => {
  if (selectGroup.value.id == undefined) {
    ElMessage.info("请选择班组");
    return
  }
  // addLoading.value = true;
  addPeoperVisible.value = true;
  addPerperTitle.value = "添加人员"
  // saveBtn.value = true;


}

// 添加人员保存按钮
const handlePeoperSubmit = () => {
  ElMessage.error("添加人员失败");
  addPeoperVisible.value = false;
}

// 取消按钮
const handleCancel = () => {
  addGroupDialogVisible.value = false;
  addPeoperVisible.value = false;
  addGroupTitle.value = "";
  saveBtn.value = false;
  addLoading.value = false;
  dataListSelections.value = [];
  restRuleForm()
};
const restRuleForm = () => {
  ruleForm.value = {
    name: '',
    sortNo: '',
    parentId: '',
    parentName: '',
    level: '',
    id: undefined,
    createDept: undefined

  }
}
// 分页
const sizeChange = (size: number) => {
  pager.currentPage = 1
  pager.pageSize = size
  getList()

};

//   清空搜索 重置列表
const searchReset = () => {
  searchModel.value.position = ''
  searchModel.value.name = ''
  tableData.value = []
  getList()
};
const myChangeCurrent = (value: any) => {
  // 感觉这里要查第一页？？？？？
  pager.currentPage = value
  getList()
};
//移除多选
const selectionChangeHandle = (val: any) => {
  dataListSelections.value = val;
  dataListSelections.value.length == 0 ? showRestoreBtn.value = true : showRestoreBtn.value = false;
};
// 查询搜索
const searchChange = () => {
  if (selectGroup.value && selectGroup.value.id != undefined) {
    getList()
  } else {
    ElMessage.info("请选择班组");
  }
};

// 获取树形数据
const geTreeData = () => {
  companyData.value = []
  companyData.value = JSON.parse(JSON.stringify(organizes.value))
  ergodicTree(companyData.value)
  console.log(companyData.value)
}
const ergodicTree = (datas: any) => {
  for (let item of datas) {
    if (item.children && item.children.length > 0) {
      item.name = item.organizationName
      item.parentId = -1
      item.level = -1
      ergodicTree(item.children)
    } else {
      item.name = item.organizationName
      item.id = item.organizationId
      item.parentId = -1
      item.children = []
      item.level = 0
      item.createDept = item.id
      findTree(item)
    }
    console.log(companyData.value)
  }

};
const findTree = (async (data: any) => {
  const res = await getScheduleGroup({
    createDept:data.id,
    order:[
      {
        column:'sort_no',
        method:'asc'
      }
    ]
  })
  if (res?.code == '1') {
    if (res.data.length > 0) {
      data.children = res.data

    }
    console.log("-----------")
  }
})
// 获取表格数据
const getList = async () => {
  if (selectGroup.value.id == undefined) {
    ElMessage.info("请选择班组");
    return
  }
  loading.value = true;
  const payload = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
      groupId: selectGroup.value.id,
      name: searchModel.value.name,
      positionId: searchModel.value.position
    }
  };
  tableData.value = []
  const res = await getUserListByScheduleGroup(payload)
  if (res?.code == '1') {
    if (res.data && res.data.list.length > 0) {
      tableData.value = res.data.list
      tableData.value.forEach(item => {
        item.group = selectGroup.value.name
        postList.value.forEach(item1 => {
          if (item1.positionId == item.positionId) {
            item.positionName = item1.name
          }
        })
      })
      pager.total = res.data.total;
      pager.pageCount =
          Math.ceil(pager.total / pager.pageSize) === 0
              ? 1
              : Math.ceil(pager.total / pager.pageSize);
    }
  }
  loading.value = false;
}
const getPostData = async () => {
  const res = await getPostList({
    state: "VALID",
    enterpriseIds: [userInfo.value.enterpriseId],
  })
  if (res?.code === '1') {
    postList.value = res.data
  } else {
    ElMessage.error(res?.message);
  }
}
const handleOk = (list) => {
  handleCancel()
  findByCondition(companyData.value,list)
  console.log(companyData.value)
  getList()
}

onMounted(() => {
  geTreeData();
  getPostData()

})
</script>

<style scoped lang="less">
@import url("../style/publicStyle.less");

.container {
  .el-input__icon {
    font-size: 18px;
    margin-left: 10px;
  }

  .tableColumns {
    .left-tree {
      min-width: 300px;
      max-width: 300px;

      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
        width: 250px;

        .custom-tree-node-left {
          max-width: 125px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .oper {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          user-select: none;
          padding-right: 0;
          width: 80px;

          img {
            width: 20px;
            height: 20px;
            object-fit: contain;

            &:hover {
              transform: scale(1.1);
            }
          }

          img + img {
            margin-left: 8px;
          }

          .border {
            border-radius: 4px;
            border: 1px solid #2f7df1;
            padding: 2px;
            box-sizing: border-box;
            margin-left: 8px;
          }
        }
      }
    }

    ::v-deep .el-tree-node > .el-tree-node__children {
      overflow: hidden;
    }

    .table-select {
      height: auto !important;
    }
    .el-checkbox.el-checkbox--large{
      height:2rem
    }
    //::v-deep .el-form-item__content{
    //  flex-wrap: nowrap;
    //}

  }
}
</style>
